/**
* Copyright (c) 2025 Huawei Technologies Co., Ltd.
* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
* CANN Open Software License Agreement Version 2.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
*/

#include <cstdint>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include "acl/acl.h"
#include "kernel_operator.h"
#include "data_utils.h"

constexpr uint32_t BUFFER_NUM = 2; // tensor num for each queue

struct AddCustomTilingData {
    uint32_t singleCoreLength;
};

using AscendC::TPosition;
namespace {
constexpr uint32_t TILE_LENGTH = 4096;
}

class KernelAddV3 {
public:
    __aicore__ inline KernelAddV3() = default;
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR y, GM_ADDR z, uint32_t singleCoreLength)
    {
        xGm.SetGlobalBuffer((__gm__ float *)x + AscendC::GetBlockIdx() * singleCoreLength, singleCoreLength);
        yGm.SetGlobalBuffer((__gm__ float *)y + AscendC::GetBlockIdx() * singleCoreLength, singleCoreLength);
        zGm.SetGlobalBuffer((__gm__ float *)z + AscendC::GetBlockIdx() * singleCoreLength, singleCoreLength);
        loopCount = singleCoreLength / TILE_LENGTH;
    }

    __aicore__ inline void Process()
    {
        // use local memory allocator to simplify memor allocation
        AscendC::LocalMemAllocator<AscendC::Hardware::UB> ubAllocator;
        // ping
        AscendC::LocalTensor<float> xLocalPing = ubAllocator.Alloc<float, TILE_LENGTH>();
        AscendC::LocalTensor<float> yLocalPing = ubAllocator.Alloc<float, TILE_LENGTH>();
        AscendC::LocalTensor<float> zLocalPing = ubAllocator.Alloc<float, TILE_LENGTH>();
        // pong
        AscendC::LocalTensor<float> xLocalPong = ubAllocator.Alloc<float, TILE_LENGTH>();
        AscendC::LocalTensor<float> yLocalPong = ubAllocator.Alloc<float, TILE_LENGTH>();
        AscendC::LocalTensor<float> zLocalPong = ubAllocator.Alloc<float, TILE_LENGTH>();

        // double buffer
        AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID0);
        AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID1);
        for (uint32_t i = 0; i < loopCount; i++) {
            int32_t eventID = (i % 2 == 0 ? EVENT_ID0 : EVENT_ID1);
            AscendC::LocalTensor<float> &xLocal = (i % 2 == 0 ? xLocalPing : xLocalPong);
            AscendC::LocalTensor<float> &yLocal = (i % 2 == 0 ? yLocalPing : yLocalPong);
            AscendC::LocalTensor<float> &zLocal = (i % 2 == 0 ? zLocalPing : zLocalPong);
            // dependency of PIPE_MTE3 & PIPE_MTE2 caused by xLocal/yLocal between 2 sequential loops
            AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(eventID);
            AscendC::DataCopy(xLocal, xGm[i * TILE_LENGTH], TILE_LENGTH);
            AscendC::DataCopy(yLocal, yGm[i * TILE_LENGTH], TILE_LENGTH);

            // dependency of PIPE_MTE2 & PIPE_V caused by xLocal/yLocal in one single loop
            AscendC::SetFlag<AscendC::HardEvent::MTE2_V>(eventID);
            AscendC::WaitFlag<AscendC::HardEvent::MTE2_V>(eventID);
            AscendC::Add(zLocal, xLocal, yLocal, TILE_LENGTH);
            // dependency of PIPE_V & PIPE_MTE3 caused by zLocal in one single loop
            AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(eventID);
            AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(eventID);
            AscendC::DataCopy(zGm[i * TILE_LENGTH], zLocal, TILE_LENGTH);
            // dependency of PIPE_MTE3 & PIPE_MTE2 caused by zLocal between 2 sequential loops
            AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(eventID);
        }
        AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID0);
        AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID1);
    }

private:
    AscendC::GlobalTensor<float> xGm;
    AscendC::GlobalTensor<float> yGm;
    AscendC::GlobalTensor<float> zGm;
    uint32_t loopCount;
};

struct ArgInfo {
    std::string fileName;
    size_t length;
};


__global__ __aicore__ void add_custom(GM_ADDR x, GM_ADDR y, GM_ADDR z, GM_ADDR tiling)
{
    KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY);
    KernelAddV3 op;
    op.Init(x, y, z, ((__gm__ AddCustomTilingData *)tiling)->singleCoreLength);
    op.Process();
}

void KernelCall(uint32_t blockDim, void *stream, std::vector<ArgInfo> &inputsInfo,
    std::vector<ArgInfo> &outputsInfo, uint8_t *tiling)
{
    std::vector<uint8_t *> inputHost(inputsInfo.size());
    std::vector<uint8_t *> inputDevice(inputsInfo.size());
    std::vector<uint8_t *> outputHost(outputsInfo.size());
    std::vector<uint8_t *> outputDevice(outputsInfo.size());
    uint8_t *tilingDevice;

    aclrtMalloc((void **)(&tilingDevice), sizeof(AddCustomTilingData), ACL_MEM_MALLOC_HUGE_FIRST);
    aclrtMemcpy(
        tilingDevice, sizeof(AddCustomTilingData), tiling, sizeof(AddCustomTilingData), ACL_MEMCPY_HOST_TO_DEVICE);

    for (uint32_t i = 0; i < inputsInfo.size(); i++) {
        aclrtMallocHost((void **)(&inputHost[i]), inputsInfo[i].length);
        aclrtMalloc((void **)(&inputDevice[i]), inputsInfo[i].length, ACL_MEM_MALLOC_HUGE_FIRST);
        ReadFile(inputsInfo[i].fileName, inputsInfo[i].length, inputHost[i], inputsInfo[i].length);
        aclrtMemcpy(
            inputDevice[i], inputsInfo[i].length, inputHost[i], inputsInfo[i].length, ACL_MEMCPY_HOST_TO_DEVICE);
    }

    for (uint32_t i = 0; i < outputsInfo.size(); i++) {
        aclrtMallocHost((void **)(&outputHost[i]), outputsInfo[i].length);
        aclrtMalloc((void **)(&outputDevice[i]), outputsInfo[i].length, ACL_MEM_MALLOC_HUGE_FIRST);
    }

    add_custom<<<blockDim, nullptr, stream>>>(inputDevice[0], inputDevice[1], outputDevice[0], tilingDevice);
    aclrtSynchronizeStream(stream);

    aclrtFree(tilingDevice);
    for (uint32_t i = 0; i < outputsInfo.size(); i++) {
        aclrtMemcpy(
            outputHost[i], outputsInfo[i].length, outputDevice[i], outputsInfo[i].length, ACL_MEMCPY_DEVICE_TO_HOST);
        WriteFile(outputsInfo[i].fileName, outputHost[i], outputsInfo[i].length);
        aclrtFree(outputDevice[i]);
        aclrtFreeHost(outputHost[i]);
    }

    for (uint32_t i = 0; i < inputsInfo.size(); i++) {
        aclrtFree(inputDevice[i]);
        aclrtFreeHost(inputHost[i]);
    }
}

int32_t main(int32_t argc, char *argv[])
{
    uint32_t blockDim = 8;
    // set data length, in this case we use 8 cores and length of each core is 4096 * 9
    uint32_t dataLen = 4096 * 9 * blockDim;
    size_t inputByteSize = dataLen * sizeof(float);
    size_t outputByteSize = dataLen * sizeof(float);
    AddCustomTilingData tiling;
    tiling.singleCoreLength = dataLen / blockDim;

    std::vector<ArgInfo> inputsInfo = {{"./input/input_x.bin", inputByteSize}, {"./input/input_y.bin", inputByteSize}};
    std::vector<ArgInfo> outputsV3Info = {{"./output/output.bin", outputByteSize}};
    
    aclInit(nullptr);
    int32_t deviceId = 0;
    aclrtSetDevice(deviceId);
    aclrtStream stream = nullptr;
    aclrtCreateStream(&stream);

    KernelCall(blockDim, stream, inputsInfo, outputsV3Info, (uint8_t *)&tiling);
    
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}